<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\store;

use app\common\event\Base;
use app\controller\api\notify\Wechat;
use app\event\pos\AfterSaleModel;
use app\event\pos\ComplaintModel;
use app\event\pos\CouponCardModel;
use app\event\pos\EvaluateEvent;
use app\event\pos\PayEvent;
use app\event\pos\UserBalanceEvent;
use app\event\store\Address as AddressEvent;
use app\model\pay\Pay as PayModel;
use app\model\pos\PosTransfer as PosTransferModel;
use app\model\pos\PosVip as PosVipModel;
use app\model\pos\Pos as PosModel;
use app\model\store\DepositOrder as DepositOrderModel;
use app\event\ucenter\Notice as NoticeEvent;
use app\model\pos\DepositOrderVip as DepositOrderVipModel;
use app\model\pos\DepositOrderItem as DepositOrderItemModel;
use app\model\pos\PosLevel as PosLevelModel;
use app\model\pos\UserPosLevel as UserPosLevelModel;
use app\model\store\Good as GoodModel;
use app\model\store\Order as OrderModel;
use app\model\store\Store as StoreModel;
use app\model\ucenter\User as UserModel;
use app\model\pos\PosItem as PosItemModel;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use wechat\mch\Pay as WechatMchPay;
use wechat\official_account\Template as TemplateOfficial;

class DepositOrder extends Base
{
    /**
     * 发送者
     * @var UserModel
     */
    protected UserModel $user;
    /**
     * 参数
     * @var array
     */
    protected array $param;


    /**
     * 卖家信息
     * @var StoreModel
     */
    private $store;

    /**
     * 当前订单
     * @var OrderModel
     */
    private $order = [];
    /**
     * 当前宝贝
     * @var GoodModel
     */
    private $good = [];
    /**
     * 当前宝贝
     * @var CouponCardModel
     */
    private $coupon = [];
    /**
     * @var array
     */
    private $orders = [];
    /**
     * @var array
     */
    private $pays = [];
    /**
     * 订单来自
     * @var int
     */
    private $from = 3;

    /**
     * 发货
     * @param array $param
     * @param UserModel $admin
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function send($param, $admin, $rule = 'admin')
    {
        try {

            $order = DepositOrderModel::where('id', $param['id'])->where('status', 2)->find();
            if (!$order) {
                throw new Exception('订单不存在');
            }

            Db::startTrans();

            if ($order['send_type'] == 1) {
                $order['express_sn'] = $param['express_sn'];
                $order['express_name'] = $param['express_name'];

                $order['status'] = 5;
                $param = [];
                $param['type'] = 'send_deposit';
                $param['relation_id'] = $order['id'];
                NoticeEvent::send($param, $order->user);
            } else {
                $order['status'] = 5;
            }
            $order['send_time'] = time_format();
            if (!$order->save()) {
                throw new Exception('订单保存失败');
            }
            if ($order['send_type'] == 1) {
                $param = [];
                $param['type'] = 'send_deposit';
                $param['relation_id'] = $order['id'];
                NoticeEvent::send($param, $order->user);
            }
            Db::commit();
            // 返回订单数据
            $data['code'] = 0;
            $data['message'] = '发货成功';
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 订单详情
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function detail($param, $user, $rule = 'store')
    {
        try {
            if (empty($param['id'])) {
                throw new Exception('订单id不存在');
            }
            if ('user' == $rule) {

                $this->order = $user->orders()->with(['goods' => ['cover', 'sku'], 'address', 'payment', 'pay', 'logs', 'express', 'store'])->where('id', $param['id'])->find();
            } else {
                $store = $this->request->store;
                $this->order = $store->orders()->with(['goods', 'logs'])->where('id', $param['id'])->find();
            }
            if (!$this->order) {
                throw new Exception('查无订单');
            }
            // 返回订单数据
            $data['code'] = 0;
            $data['data'] = $this->order;
        } catch (Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 确认收货
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function confirm($param, $user, $role = 'user')
    {
        try {
            // 订单查询
            $this->order = DepositOrderModel::where('status', 3)->where('user_id', $user['id'])->where('id', $param['id'])->find();
            if (!$this->order) {
                throw new Exception('订单不存在');
            }
            $this->_confirm($this->order, $user, $role);
            // 返回订单数据
            $data['code'] = 0;
            $data['message'] = '成功';
        } catch (Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 确认收货
     * @param OrderModel $order
     * @param UserModel $user
     * @param string $role
     * @param string $message
     * @return void
     * @throws Exception
     */
    protected function _confirm($order, $user, $role = 'user', $message = '订单已收货')
    {

        if ($order['status'] != 3) {
            throw new Exception('订单状态异常');
        }
        //更改订单状态
        $order['finish_time'] = time_format();
        $order['status'] = 5;
        $order->save();
        // 增加订单日志
//        $log['message'] = $message;
//        $log['user_id'] = $user['id'];
//        $log['role'] = $role;
//        $log['order_status'] = $order['status'];
//        $order->log()->save($log);
    }

    /**
     * 再次支付
     * @param array $param 提交信息
     * @param UserModel $user 用户对象信息
     * @return array
     */
    public function repay($param, $user)
    {
        $this->user = $user;
        $this->param = $param;
        try {
            $order = DepositOrderModel::where('id', $param['id'])->order('user_id', $user['id'])->find();
            if ($order['status'] < 1) {
                throw new Exception('订单已经被取消');
            }
            if ($order['status'] > 1) {
                throw new Exception('订单已经支付');
            }
            // 查询支付信息
            $pay = PayModel::where('type', 'pos')->where('relation_id', $order['id'])->find();
            if (!$pay) {
                throw new Exception('订单已经超时');
            }
            if ($pay['status'] == 1) {
                throw new Exception('订单已经支付');
            }
            // 返回订单数据
            $data['code'] = 0;
            $data['data']['order'] = $order;
            if ($user['id'] == 16006) {
                $pay_param['out_trade_no'] = $pay['pay_sn'];
                $pay_param['trade_type'] = 'APP';
                $pay_param['notify_url'] = (string)url('pay/Wechat/notify', [], true, true);
                $pay_param['total_fee'] = $pay['total_amount'] * 100;
                //  $pay_param['total_fee'] = 1;
                $pay_param['attach'] = $pay['type'];
                $pay_param['detail'] = '';// 保留
                $pay_param['body'] = '商品支付';
                $pay_param['device_info'] = 'app';
                $WechatMchPay = new WechatMchPay('wx7c83e79f78fdfa10', '1697093647', 'qC04wNxXUFVv2eEItzWpdb8BSPMTkHln');
                $pay_result = $WechatMchPay->unifiedorder($pay_param);
                if ('fail' == strtolower($pay_result['return_code'])) {
                    throw new Exception($pay_result['return_msg']);
                }
                if ('fail' == strtolower($pay_result['result_code'])) {
                    throw new Exception($pay_result['err_code_des']);
                }
                $orderInfo = $WechatMchPay->appSign($pay_result['prepay_id'], $pay_result['nonce_str']);
                $data['data']['pay'] = ['payment' => 'wxpay', 'order_info' => $orderInfo];;
            } else {

                $data['data']['pay'] = ['payment' => 'alipay', 'order_info' => alipay_app_pay($pay['pay_sn'], $pay['total_amount'], $pay['title'], $pay['type'])];;
            }
            $data['message'] = 'ok';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['line'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 管理员支付
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function adminPay($param, $admin)
    {
        try {
            // 订单查询
            $this->order = $user->orders()->where('status', 3)->where('id', $param['id'])->find();
            if (!$this->order) {
                throw new Exception('订单不存在');
            }
            $this->_confirm($this->order, $user, $role);
            // 返回订单数据
            $data['code'] = 0;
            $data['message'] = '成功';
        } catch (Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 预创建
     * @param array $param 提交信息
     * @param UserModel $user 下单人
     * @param int $from 1WEB2WAP3APP
     * @return array
     */
    public function preview($param, $user = null, $from = 2)
    {
        $this->param = $param;
        $this->from = $from;
        try {
            if (!$user) {
                throw new Exception('请先登录');
            }
            $this->user = $user;

            // 第1步 表单验证
            $this->_createOrderStep1(true);
//            foreach ($this->param['stores'] as $item) {
//                $order_good_all = [];
//                $store = $item['store'];
//                $this->orders[] = $this->_preCreate($item['goods_sku'], $store, $order_good_all, true);
//            }


            $data['code'] = 0;
            $data['data']['order'] = $this->_buildOrderData();
            $data['data']['cart'] = $this->param['cart'];
        } catch (Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['line'] = $e->getLine();
            $data['file'] = $e->getFile();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 创建订单
     * @param array $param 提交信息
     * @param UserModel $user 店铺
     * @param int $from 1WEB2WAP3APP
     * @return array
     */
    public function create($param, $user, $from = 2)
    {
        $this->param = $param;
        $this->from = $from;
        $this->user = $user;
        try {
            Db::startTrans();
            // 第1步 表单验证
            $this->_createOrderStep1();
            // 第2步 创建订单信息
            $this->_createOrderStep2();
            // 第5步 订单后续处理
            $this->_createOrderStep6();

            // 第3步 订单后续处理
            // 提交事务
            Db::commit();
            // 返回订单数据
            $data['code'] = 0;
            $data['data']['order'] = $this->param['order'];
            $data['message'] = '订单创建成功';
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 1;
            $data['line'] = $e->getLine();
            $data['file'] = $e->getFile();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 订单生成前的数据验证与处理
     * @param bool $preview
     * @return void
     * @throws Exception
     */
    private function _createOrderStep1(bool $preview = false): void
    {

        if ($this->user['realName'] != 1) {
            throw new Exception('请先实名');
        }

        if (empty($this->param['address']['id'])) {
            // 为空新增地址
            $event = new AddressEvent();
            $data = $event->update($this->param['address'], $this->user);
            if ($data['code'] == 1) {
                throw new Exception($data['message']);
            }
            $address = $data['data'];
            if ($address) {
                $address = $address->toArray();
                unset($address['id']);
                unset($address['create_time']);
                unset($address['update_time']);
            }

        }else{
            $address = $this->param['address'];
        }

        $this->param['address'] = $address;
    }

    protected function _buildOrderData()
    {
        $order['name'] = '升级礼包领取订单';

        $order['user_id'] = $this->user['id'];
        $order['agent_id'] = $this->user['agent_id'];
        $order['remark'] = isset($this->param['remark']) ? $this->param['remark'] : '';
        $order['size_name'] = isset($this->param['size_name']) ? $this->param['size_name'] : '';
        $order['send_type'] = 1;
        $order['number'] = 1;
        $order['good_amount'] = 298;
        $order['pay_amount'] = 298;
        $order['shipping_amount'] = 0;
        $order['address_info'] = $this->param['address'];
        $order['amount'] = $order['good_amount'] + $order['shipping_amount'];
        $order['status'] = 2;
        return $order;
    }

    /**
     * 初始化订单信息
     * @throws Exception
     */
    private function _createOrderStep2(): void
    {
//        $this->param['order'] = $this->_buildOrderData();
        $this->param['order'] = DepositOrderModel::create($this->_buildOrderData());
    }


    /**
     * 订单后续其它处理
     */
    private function _createOrderStep6()
    {
        // 清空购物车
    }

    /**
     * 修改订单支付状态，需要其他Event调用
     * @param                $pay
     * @param null|UserModel $admin
     * @return OrderModel
     * @throws Exception
     * @author 微尘 <yicmf@qq.com>
     */


    /**
     * 定时取消未支付订单
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     * @datetime: 2019/8/27 15:31
     */
//    public function systemCancel()
//    {
//        try {
//            $orders = OrderModel::where('status', 1)
//                ->whereTime('create_time', '<', '-' . (int)Config::get('store.order_auto_cancel_time') . ' hours')->select();
//            $this->user = UserModel::where('id', Config::get('ucenter.system_notice_from_user_id'))->find();
//            foreach ($orders as $index => $order) {
//                // 开启事务
//                Db::startTrans();
//                $this->order = $order;
//                $this->store = $this->order->store;
//                $this->_cancel('超时未支付【' . $this->user['nickname'] . '】取消了订单', 'system');
//                // 提交事务
//                Db::commit();
//            }
//            // 取消超时未发货订单
//            $order_wait_send = (int)Config::get('store.order_wait_send');
//            if ($order_wait_send > 0) {
//                $orders = OrderModel::where('status', 2)
//                    ->whereTime('payment_time', '<', '-' . $order_wait_send . ' hours')->select();
//                foreach ($orders as $index => $order) {
//                    // 开启事务
//                    Db::startTrans();
//                    $this->order = $order;
//                    $this->store = $this->order->store;
//                    $this->_cancel('超时未发货【' . $this->user['nickname'] . '】取消了订单', 'system');
//                    // 提交事务
//                    Db::commit();
//                }
//            }
//            $data['message'] = '删除成功';
//            $data['code'] = 0;
//        } catch (Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            Log::record('订单删除出错：' . $e->getMessage());
//            $data['code'] = 1;
//            $data['message'] = $e->getMessage();
//        }
//        return $data;
//    }


    /**
     * 卖家点击确认收款
     * @param array $param
     * @param StoreModel $store
     * @param UserModel $user
     * @return mixed
     * @author  : 微尘 <yicmf@qq.com>
     * @datetime: 2019/2/20 10:57
     */
    public function salePay($param, $store = null, $user = null)
    {
        try {
            // 开启事务
            Db::startTrans();
            $this->order = $store->orders()->where('id', $param['id'])->find();
            if (!$this->order) {
                throw new Exception('未发现要删除的订单', 56001);
            }
            if ($this->order['status'] != 0) {
                throw new Exception('当前订单状态不可删除');
            }
            //                if (1 < $this->order['status']) {
            //                    //已经付款的订单需要在90天后删除;
            //                    if (($this->request->time() - $this->order->getData('create_time')) / 86400 < 90) {
            //                        throw new Exception('暂不可删除90日内订单');
            //                    }
            //                }
            if ($this->order['delete_status'] == 2 && $this->order['delete_status'] == 3) {
                throw new Exception('当前订单已经删除');
            }
            if ($this->order['delete_status'] == 1) {
                $this->order['delete_status'] = 3;
                //                 $this->order['status'] = -2;
            } else {
                $this->order['delete_status'] = 2;
            }
            $this->order->save();
            $log = [];
            $log['role'] = 'sale';
            $log['user_id'] = $user['id'];
            $log['order_status'] = $this->order['status'];
            $log['message'] = '【' . $user['nickname'] . '】删除了订单';
            // 增加日志
            $this->order->logs()->save($log);
            // 提交事务
            Db::commit();
            $data['message'] = '删除成功';
            $data['code'] = 0;
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::record('订单删除出错：' . $e->getMessage());
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 修改订单支付状态，需要其他Event调用
     * @param                $pay
     * @param null|UserModel $admin
     * @return OrderModel
     * @throws Exception
     * @author 微尘 <yicmf@qq.com>
     */
    public function pay($pay, $admin = null)
    {
        $this->order = DepositOrderModel::where('id', $pay['relation_id'])->lock(true)->find();
        if (!$this->order) {
            throw new Exception('订单不存在');
        }
        if (1 != $this->order['status']) {
            throw new Exception('订单状态异常');
        }
        // 更改订单

        $this->order['status'] = 2;
        $this->order['pay_time'] = time_format();
        if (!$this->order->save()) {
            throw new Exception('订单状态异常：订单状态改变错误 ');
        }

//        $wechat = new Wechat();
//        $wechat->payOrder($this->order);

        $account['token'] = 'yunfuye';
        $account['encoding_aes_key'] = 'BkrUUPz9IgfERTRXmwiIf0RSir4ONBku64EufsZ9EE2';
        $account['app_secret'] = 'cbdd44c7d119c8b4dd51b74c3030aa75';
        $account['app_id'] = 'wxd4cc6bfc61b75cc5';
        $oa = new TemplateOfficial();
        $oa->initAccount($account);
//            $WechatTemplate = WechatTemplateModel::where('wechat_no', 'OPENTM401627381')->where('status', 1)->find();
        $data = [
            'amount7' => ['value' => $this->order['amount'], 'color' => '#000000'],
            'character_string6' => ['value' => $this->order['sn'], 'color' => '#000000'],
            'time5' => ['value' => $this->order['create_time'], 'color' => '#000000'],
            'phone_number4' => ['value' => $this->order['user']['username'], 'color' => '#000000'],
            //                'keyword1'=> ['value'=>$auth['idcard_name'], 'color'=>'#000000'],
            //                'keyword2'=> ['value'=>time_format(), 'color'=>'#000000'],
            'thing8' => ['value' => $this->order['user']['nickname'], 'color' => '#000000'],
        ];
//小花
        $re = $oa->send('oAAIg6zwyPLf6jeOUBvWazwzA2qU', 'rYCxbRngE4XXD_D4Lhg25n9jM9psopW6rJXZtVlU-Es', $data, '');
        //张点成
        $re = $oa->send('oAAIg61CfAjbBmIPUojwc87FsQBA', 'rYCxbRngE4XXD_D4Lhg25n9jM9psopW6rJXZtVlU-Es', $data, '');
        // 微尘
        $re = $oa->send('oAAIg6w_C0wy7_rmcb3VahTohD6s', 'rYCxbRngE4XXD_D4Lhg25n9jM9psopW6rJXZtVlU-Es', $data, '');
        //张琦
        $re = $oa->send('oAAIg622danHy6GAlzK5v4uZsou0', 'rYCxbRngE4XXD_D4Lhg25n9jM9psopW6rJXZtVlU-Es', $data, '');
//        /
        // oAAIg622danHy6GAlzK5v4uZsou0增加日志
//        $log = [];
//        $log['message'] = '完成了支付订单';
//        $log['role'] = 'user';
//        $log['order_status'] = $this->order['status'];
//        $this->order->logs()->save($log);
        // 订单通知及统计
        $param = [];
        $param['order_id'] = $this->order['id'];
        $param['type'] = 'pay_order';
        // 发送店铺通知
        NoticeEvent::send($param, $this->order->user);
        return $this->order;
    }

    /**
     * 修改订单支付状态，需要其他Event调用
     * @param                $pay
     * @param null|UserModel $admin
     * @return OrderModel
     * @throws Exception
     * @author 微尘 <yicmf@qq.com>
     */
    public function adminPay2($param, $admin = null)
    {
        $this->order = DepositOrderModel::where('id', $param['id'])->lock(true)->find();
        if (!$this->order) {
            throw new Exception('订单不存在');
        }
        if (1 != $this->order['status']) {
            throw new Exception('订单状态异常');
        }
        // 更改订单

        $this->order['status'] = 2;
        if (!$this->order->save()) {
            throw new Exception('订单状态异常：订单状态改变错误 ');
        }
        $data['code'] = 0;
        $data['message'] = 'ok';
        return $data;

    }

    /**
     * 买家取消订单，取消未付款订单
     * @param array $param
     * @param UserModel $user
     * @return array
     */
    public function buyCancel($param, $user = null)
    {
        try {
            $this->user = $user;
            // 订单查询
            $this->order = DepositOrderModel::where('status', 1)->where('user_id', $user['id'])->where('id', $param['id'])->find();
            if (!$this->order) {
                throw new Exception('订单不存在');
            }
            if (!$this->order) {
                throw new Exception('未发现要取消订单', 56001);
            }
//            if (!in_array($this->order['status'], [1, 2, 3, 4, 5])) {
//                throw new Exception('当前订单状态无法取消');
//            }
            // 开启事务
            Db::startTrans();
            $this->_cancel(isset($param['reason']) ? $param['reason'] : null, 'user');
            // 发送用户消息
            // 提交事务
            Db::commit();
            $data['code'] = 0;
            $data['message'] = '取消成功';
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::record('订单取消出错：' . $e->getMessage());
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 售后退款
     * @param AfterSaleModel $after
     * @param UserModel $user
     * @param string $role
     * @return AfterSaleModel
     */
    public function afterRefund($after, $user, $role)
    {
        // 操作退款
        //TODO:积分抵红包扣比例
        $this->order = $after->order;

        // 退款
        $pay = $this->order->pay()->where('status', 1)->find();
        $payEvent = new PayEvent();
        $result = $payEvent->afterRefund($pay, $after);
        if (0 !== $result['code']) {
            throw new Exception($result['message']);
        }
        if ($this->order['status'] == 5) {
            // 订单已经收货，需要扣除卖家余额
            // 扣除卖家保证金，给用户退款
            $change = [];
            $change['relation_id'] = $after['id'];
            $change['amount'] = -$after['amount'];
            $change['change_code'] = 'after_sale';
            $change['message'] = '售后退款';
            UserBalanceEvent::change($change, $this->order->seller);
//				$log = StoreCreditDepositEvent::change($change, $store);
        }
        $this->order['lock_status'] = 0;
        $this->order['refund_amount'] = $this->order['refund_amount'] + $after['amount'];
        $this->order['refund_time'] = time_format();
        $this->order['cost_amount'] = $this->order->goods()->where('is_refund', 0)->where('status', 1)->sum('cost_price');
        $this->order['profit'] = $this->order['real_amount'] - $this->order['refund_amount'] - $this->order['cost_amount'];

        // 如果都退款，订单状态关闭
        if (!$this->order->goods()->where('is_refund', 0)->where('status', 1)->find()) {
            $this->order['cancel_reason'] = '当前订单关联的已经全部退货，自动自动取消';
            $this->order['cancel_time'] = time_format();
            $this->order['status'] = 0;
            //恢复优惠券
//				if ($this->order['promotion_amount'] > 0) {
//					$this->order->coupons()->update(['already_used' => 0, 'order_id' => null]);
//				}
        }

        if (!$this->order->save()) {
            throw new Exception('订单信息保存失败');
        }
        // 增加日志
        $log = [];
        $log['role'] = $role;
        $log['user_id'] = $user['id'];
        $log['order_status'] = $this->order['status'];
        $log['message'] = '【' . $user['nickname'] . '】完成售后订单';
        $this->order->logs()->save($log);

        // 库存退回
        if ($after['good_status'] == 0 || ($after['good_status'] == 1 && $after['type'] == 1)) {
            $after['good']['sku']['stock'] = $after['good']['sku']['stock'] + $after['good']['number'];
            $after['good']['sku']->save();
            $after['good']['good']['stock'] = $after['good']['good']['stock'] + $after['good']['number'];
            $after['good']['good']->save();
        }
        return $after;
    }

    /**
     * 用户投诉完成
     * @param ComplaintModel $complaint
     * @param UserModel $user
     * @throws Exception
     * @author 微尘 <yicmf@qq.com>
     * @datetime: 2020/2/16 13:56
     */
    public function complaintFinish($complaint, $user = null)
    {
        $this->order = OrderModel::where('id', $complaint['order_id'])->find();
        $this->order['lock_status'] = 0;
        if (1 == $complaint['result']) {
            // 取消订单
            if (!in_array($this->order['status'], [1, 2, 3, 4, 5])) {
                throw new Exception('当前订单状态无法取消');
            }
            $this->_cancel('投诉成功取消订单', 'store');
        } else {
            // 投诉失败，订单解锁
            $this->order->save();
        }
        $this->store = $this->order->store()->find();

        $param = [];
        $param['type'] = 'complaint_finish';
        $param['complaint_id'] = $complaint['id'];
        $param['order_id'] = $complaint['order_id'];
        // 发送用户&商家消息
        NoticeEvent::send($param, $this->store->user()->find());
    }

    /**
     * 订单取消操作
     * @param null $reason
     * @param string $role
     * @throws Exception
     * @author 微尘 <yicmf@qq.com>
     */
    private function _cancel($reason = null, $role = 'user')
    {
        if ($reason) {
            $this->order['cancel_reason'] = $reason;
        }
        $this->order['cancel_time'] = time_format();
        $this->order['status'] = 0;
        //恢复优惠券
//			if ($this->order['coupon_amount'] > 0) {
//				$this->order->coupons()->update(['already_used' => 0, 'order_id' => null]);
//			}
        if (!$this->order->save()) {
            throw new Exception('取消订单信息保存失败');
        }
        // 增加日志
//        $log = [];
//        $log['role'] = $role;
//        $log['user_id'] = $this->user['id'];
//        $log['order_status'] = $this->order['status'];
//        $log['message'] = '【' . $this->user['nickname'] . '】取消了订单';
//        $this->order->logs()->save($log);
        // 库存退回
        PosModel::where('order_id', $this->order['id'])->update(['order_id' => null, 'user_id' => null, 'buy_user_id' => null]);
//        $notice = [];
//        $notice['type'] = 'cancel_order';
//        $notice['title'] = '订单取消';
//        $notice['content'] = $reason;
//        $notice['relation_id'] = $this->order['id'];
//        NoticeEvent::send($notice, $this->order->user);
    }

    /**
     * 检查商品是否可以购买
     * @param GoodModel $good
     * @param UserModel $user
     * @throws Exception
     */
    protected function _buyCheckGood($good, $user, $number = 1)
    {
        if (!$good) {
            throw new Exception('商品【' . $good['title'] . '】不可购买');
        }
        if (1 == $good['is_deny']) {
            throw new Exception('商品【' . $good['title'] . '】违规下架！');
        }
        if (1 == $good['is_deny']) {
            throw new Exception('商品违规下架！');
        }
        if ($good['buy_start'] > 0 && $good['buy_start'] > $number) {
            throw new Exception('最低购买' . $good['buy_start'] . '个！');
        }
        if ($good['buy_max'] > 0 && $good['buy_max'] < $number) {
            throw new Exception('最多购买' . $good['buy_max'] . '个！');
        }
        // 购买间隔
        if ($good['buy_range'] > 0 && OrderModel::where('ip', $this->request->ip())->whereTime('create_time', '>', '-' . $good['buy_range'] . ' minute')->find()) {
            throw new Exception('请在' . $good['buy_range'] . '分钟后下单！');
        }
        // 验证以及处理库存
        if ($good['stock'] < $number) {
            throw new Exception('商品【' . $good['title'] . '】库存不足！');
        }
    }


    /**
     * 取消超时未付款订单指定
     * @param array $data
     * @return array
     */
    public function timeoutClose(array $data = []): array
    {
        try {

            if (isset($data['order_id'])) {
                $orders = DepositOrderModel::where('status', 1)->where('id', $data['order_id'])->select();
            } else {
                // 批量查询超时订单
                $orders = DepositOrderModel::where('status', 1)->whereTime('limit_time', '<', 'now')->select();
            }
            foreach ($orders as $index => $order) {
                // 开启事务
                Db::startTrans();
                $this->order = $order;
                $this->_cancel('超时未支付取消了订单', 'system');
                // 提交事务
                Db::commit();
            }
            $data['code'] = 0;
            $data['message'] = '取消成功' . count($orders) . '个订单';
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::record('系统订单取消出错：' . $e->getMessage());
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;

    }

    /**
     * 自动完成评价
     * @param $data
     * @return array
     */
    public function systemEvaluate($data): array
    {
        try {

            $orders = OrderModel::where('status', 1)
                ->where('evaluation_status', 5)
                ->whereTime('finish_time', '<', '-15 days')->select();
            $this->user = UserModel::where('id', Config::get('ucenter.system_notice_from_user_id'))->find();
            $evaluate = new EvaluateEvent();
            foreach ($orders as $index => $order) {
                $re = $evaluate->system($order);
                if ($re['code'] != 0) {
                    Log::write('plan:' . $re['code']);
                }
            }
            // 发送用户消息
            $data['code'] = 0;
            $data['message'] = '取消成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;

    }


}
